﻿Imports System.IO
Imports System.Environment
Imports Microsoft.Win32
Public Class MaintenancePage

    Private Sub MaintenancePage_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        GroupBox2.Enabled = False
        GroupBox4.Enabled = False
        GroupBox5.Enabled = False
        TextHost.Text = My.Settings.dbhost
        TextUsername.Text = My.Settings.dbuser
        TextPassword.Text = My.Settings.dbpassword
        TextPort.Text = My.Settings.dbport
        TextDatabase.Text = My.Settings.dbname
    End Sub
    Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged
        GroupBox2.Enabled = False
        GroupBox4.Enabled = False
        GroupBox5.Enabled = False
        If RadioButton1.Checked Then
            GroupBox5.Enabled = True
        End If
    End Sub

    Private Sub RadioButton2_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton2.CheckedChanged
        GroupBox2.Enabled = False
        GroupBox4.Enabled = False
        GroupBox5.Enabled = False
        If RadioButton2.Checked Then
            GroupBox2.Enabled = True
        End If
    End Sub

    Private Sub RadioButton3_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton3.CheckedChanged
        GroupBox2.Enabled = False
        GroupBox4.Enabled = False
        GroupBox5.Enabled = False
        If RadioButton3.Checked Then
            GroupBox4.Enabled = True
        End If
    End Sub
    Public Function testkoneksi(ByRef errmsg As String, ByVal parameterkoneksi As Object()) As Boolean
        Dim ReturnValue As Boolean = False
        Dim clsmysql As NetToolMysql_v12.NetMysql
        Try
            clsmysql = New NetToolMysql_v12.NetMysql(parameterkoneksi(0), parameterkoneksi(1), _
                                                               parameterkoneksi(2), parameterkoneksi(3), _
                                                               parameterkoneksi(4))
            ReturnValue = clsmysql.TesConnection(errmsg)
        Catch ex As Exception
            errmsg = ex.Message
            ReturnValue = False
        End Try
        Return ReturnValue
    End Function
    Private Sub btnBACK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBACK.Click
        Dim errmsg As String = ""
        If testkoneksi(errmsg, New Object() {TextDatabase.Text, _
                                       TextHost.Text, _
                                       TextUsername.Text, _
                                       TextPassword.Text, _
                                       TextPort.Text}) Then



            MessageBox.Show("Test Connection Successed", "Tes Koneksi")
        Else
            MessageBox.Show("Error Tes Koneksi" & vbCrLf & errmsg, "Tes Koneksi")
        End If
    End Sub
    Private folderName As String
    Private Sub SimpleButton3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton3.Click

        If (TextDatabase.Text = "") Or (TextHost.Text = "") Or (TextUsername.Text = "") Or (TextPort.Text = "") Then
            MessageBox.Show("Maaf Silahkan Lengkapi Database Setting anda !", "Get MySql Connection")
            Exit Sub
        End If
        Dim result As DialogResult = folderBrowse.ShowDialog()
        If (result = Windows.Forms.DialogResult.OK) Then
            folderName = folderBrowse.SelectedPath
            If Microsoft.VisualBasic.Right(folderName, 1) = "\" Then
                LblPath.Text = folderName & TextDatabase.Text & Now.ToString("yyyyMMdd_hhmm") & ".sql"
            Else
                LblPath.Text = folderName & "\" & TextDatabase.Text & Now.Date.ToString("yyyyMMdd_hhmm") & ".sql"
            End If
        End If
    End Sub
    Private Sub Backup()
        'Try
        If File.Exists(LblPath.Text) Then
            File.Delete(LblPath.Text)
        End If

        If TextPassword.Text = "" Then
            'Process.Start(Application.StartupPath & "\mysqldump.exe", "--user=" & TextUsername.Text & " --host=" & TextHost.Text & " -B -C -R " & TextDatabase.Text & " > -r """ & LblPath.Text & """")
            'Process.Start(Application.StartupPath & "\mysqldump.exe", " --user=" & TextUsername.Text & " --host=" & TextHost.Text & " --databases --opt -C -R " & TextDatabase.Text & " -r """ & LblPath.Text & """")
            If RadioButton4.Checked Then
                ShellandWaitBackUp(Application.StartupPath & "\mysqldump.exe", " --user=" & TextUsername.Text & " --host=" & TextHost.Text & " -B -C -R -d " & TextDatabase.Text & " -r """ & LblPath.Text & """")
                'Process.Start(Application.StartupPath & "\mysqldump.exe", " --user=" & TextUsername.Text & " --host=" & TextHost.Text & " -B -C -R -d " & TextDatabase.Text & " -r """ & LblPath.Text & """")
            ElseIf RadioButton5.Checked Then
                ShellandWaitBackUp(Application.StartupPath & "\mysqldump.exe", " --user=" & TextUsername.Text & " --host=" & TextHost.Text & " -B -C -R " & TextDatabase.Text & " -r """ & LblPath.Text & """")
            End If

            'System.Threading.Thread.Sleep(2000)
        Else
            ShellandWaitBackUp(Application.StartupPath & "\mysqldump.exe", "--user=" & TextUsername.Text & " --password=" & TextPassword.Text & " --host=" & TextHost.Text & " -B -C -R " & TextDatabase.Text & " -r """ & LblPath.Text & """")
            'System.Threading.Thread.Sleep(2000)
        End If

        '    Return True

        'Catch ex As Exception
        '    errmsg = ex.Message
        '    Return False
        'End Try




    End Sub

    Public Sub ShellandWaitBackUp(ByVal ProcessPath As String, ByVal Arg As String)
        Dim objProcess As System.Diagnostics.Process
        Try
            objProcess = New System.Diagnostics.Process()
            objProcess.StartInfo.FileName = ProcessPath
            objProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal
            objProcess.StartInfo.Arguments = Arg

            objProcess.Start()
            Cursor = Cursors.WaitCursor
            'Wait until the process passes back an exit code 
            objProcess.WaitForExit()

            'Free resources associated with this process
            objProcess.Close()
            Cursor = Cursors.Default
            MessageBox.Show("Proses Backup selesai ", "Backup Proses")
            'File.Delete(executescript)
        Catch
            MessageBox.Show("Could not start process " & ProcessPath, "Error")
        End Try
    End Sub
    Private Sub SimpleButton4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton4.Click
        Dim errmsg As String = ""
        If Not testkoneksi(errmsg, New Object() {TextDatabase.Text, _
                                       TextHost.Text, _
                                       TextUsername.Text, _
                                       TextPassword.Text, _
                                       TextPort.Text}) Then



            MessageBox.Show("Error Tes Koneksi" & vbCrLf & errmsg, "Tes Koneksi")
            Exit Sub
        End If

        If LblPath.Text = "" Then
            MessageBox.Show("Folder Location Not Complete", "Checking Folder")
            Exit Sub
        End If
        Backup()
    End Sub

    Private Sub SimpleButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton2.Click
        If (TextHost.Text = "") Or (TextUsername.Text = "") Or (TextPort.Text = "") Then
            MessageBox.Show("Maaf Silahkan Lengkapi Setting Database anda !", "Get MySql Connection")
            Exit Sub
        End If
        OpenFileDialog1.Filter = "SQL files (*.sql)|*.SQL"

        OpenFileDialog1.FilterIndex = 2
        OpenFileDialog1.RestoreDirectory = True
        OpenFileDialog1.FileName = ""
        If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
            TextBox1.Text = OpenFileDialog1.FileName
        End If
    End Sub

    Private Sub SimpleButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton1.Click
        Dim errmsg As String = ""
        Dim tujuan As String = ""
        If Not testkoneksi(errmsg, New Object() {"mysql", _
                                       TextHost.Text, _
                                       TextUsername.Text, _
                                       TextPassword.Text, _
                                       TextPort.Text}) Then



            MessageBox.Show("Error Tes Koneksi" & vbCrLf & errmsg, "Tes Koneksi")
            Exit Sub
        End If
        If TextBox1.Text = "" Then
            MessageBox.Show("Source File Location Not Complete", "Checking File")
            Exit Sub
        End If

        'If Backup(errmsg) Then
        '    MessageBox.Show("Proses Backup selesai " & vbCrLf & "File Location = " & LblPath.Text, "Backup Proses")
        'Else
        '    MessageBox.Show("Proses Backup Terminate " & vbCrLf & errmsg, "Backup Proses")

        'End If
        'If File.Exists(Application.StartupPath & "\tempFile.bat") Then
        '    File.Delete(Application.StartupPath & "\tempFile.bat")
        'End If

        Try

            Dim fs As New FileStream(Application.StartupPath & "\tempFile.bat", FileMode.Create, FileAccess.Write)
            Dim s As New StreamWriter(fs)
            s.BaseStream.Seek(0, SeekOrigin.End)
            s.WriteLine("@echo off")

            'SetEnvironmentVariable("Path", Application.StartupPath)

            'Process.Start(Application.StartupPath & "\mysql.exe", "--user=root mysql < 'C:\Dump20110425.sql'")

            If File.Exists(TextBox1.Text) Then
                Dim strDrive As String

                Dim dirpath = GetLogicalDrives()

                For Each strDrive In dirpath
                    If strDrive.StartsWith("D") Then
                        Exit For
                    End If
                Next

                Dim splitfile As String()
                Dim filenamesplit As String = ""
                splitfile = TextBox1.Text.Split("\")
                For Each fn As String In splitfile
                    If fn.Contains(".sql") Then
                        filenamesplit = fn
                    End If
                Next
                tujuan = LSet(TextBox1.Text, 3) & "tempbackup.sql"
                File.Copy(TextBox1.Text, tujuan)

                Dim datafile As String = ""
                datafile = tujuan

                'If strDrive.StartsWith("D") Then
                '    'If File.Exists(strDrive & filenamesplit) Then
                '    '    If Not strDrive & filenamesplit = TextBox1.Text Then
                '    '        File.Delete(strDrive & filenamesplit)
                '    '        File.Copy(TextBox1.Text, strDrive & filenamesplit)
                '    '    End If                        'File.Replace(filenamesplit, strDrive, strDrive)
                '    'Else
                '    '    File.Copy(TextBox1.Text, strDrive & filenamesplit)
                '    'End If
                '    tujuan = "D:\tempbackup.sql"
                '    File.Copy(TextBox1.Text, tujuan)
                'Else
                '    strDrive = "C:\"
                '    tujuan = "C:\tempbackup.sql"
                '    File.Copy(TextBox1.Text, tujuan)
                '    'If File.Exists(strDrive & filenamesplit) Then
                '    '    File.Delete(strDrive & filenamesplit)
                '    'End If
                '    'File.Copy(TextBox1.Text, strDrive & filenamesplit)
                'End If
                'Dim datafile As String = strDrive & filenamesplit
                'datafile = tujuan

                If TextPassword.Text = "" Then
                    'Process.Start(Application.StartupPath & "\mysql.exe", "--user=root templatedbtop < ""C:\Dump20110425.sql""")
                    ''Process.Start(Application.StartupPath & "\mysql.exe", "--user=" & TextUsername.Text & " --host=" & TextHost.Text & " --databases=" & TextDatabase.Text & " < """ & TextBox1.Text & """")
                    ''Process.Start(Application.StartupPath & "\mysql.exe", "--user=" & TextUsername.Text & " --host=" & TextHost.Text & " mysql < """ & TextBox1.Text & """")
                    'System.Threading.Thread.Sleep(2000)
                    s.WriteLine("mysql --user=" & TextUsername.Text & " --host=" & TextHost.Text & " mysql < " & datafile)
                    s.Close()
                    'Process.Start(fs.Name)
                    ShellandWait(Application.StartupPath & "\tempFile.bat", tujuan)

                Else
                    s.WriteLine("mysql --user=" & TextUsername.Text & " --password=" & TextPassword.Text & " --host=" & TextHost.Text & " mysql < " & datafile)
                    s.Close()
                    ShellandWait(Application.StartupPath & "\tempFile.bat", tujuan)
                    'Process.Start(fs.Name)
                    'Process.Start(Application.StartupPath & "\mysql.exe", "--user=" & TextUsername.Text & " --password=" & TextPassword.Text & " --host=" & TextHost.Text & " " & TextDatabase.Text & " < """ & TextBox1.Text & """")
                    ''Process.Start("C:\Program Files\MySQL\MySQL Server 5.1\bin\mysql.exe", "--user=myuser --password=mypass --host=localhost --databases db_name < ""C:\BKP\back.sql""")
                    'System.Threading.Thread.Sleep(2000)
                End If

                'MessageBox.Show("Proses Restore selesai ", "Restore Proses")
            Else
                'MessageBox.Show("Proses Restore Terminate File Not Found", "Restore Proses")
            End If

        Catch ex As Exception
            errmsg = ex.Message
            MessageBox.Show("Proses Restore Terminate File Not Found" & vbCrLf & errmsg, "Restore Proses")
        End Try
    End Sub
    Public Sub ShellandWait(ByVal ProcessPath As String, ByVal executescript As String)
        Dim objProcess As System.Diagnostics.Process
        Try
            objProcess = New System.Diagnostics.Process()
            objProcess.StartInfo.FileName = ProcessPath
            objProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal
            objProcess.Start()

            'Wait until the process passes back an exit code 
            objProcess.WaitForExit()

            'Free resources associated with this process
            objProcess.Close()
            MessageBox.Show("Proses Restore selesai ", "Restore Proses")
            File.Delete(executescript)
        Catch
            MessageBox.Show("Could not start process " & ProcessPath, "Error")
        End Try
    End Sub
End Class
